package cn.com.libertymutual.sp.biz;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.service.api.CaptchaService;
import cn.com.libertymutual.sp.service.api.SmsService;

@Component
public class SendCodeBiz {

	private Logger log = LoggerFactory.getLogger(getClass());

	// 注入原子性业务逻辑
	@Resource
	private SmsService smsService;
	@Resource
	private CaptchaService captchaService;
	@Resource
	private RedisUtils redis;
	@Resource
	private IdentifierMarkBiz identifierMarkBiz;

	// 输出图形码
	public void getValidateCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		captchaService.outputCaptcha(request, response, redis);
	}

	// 发送短信验证码
	public ServiceResult smsCode(HttpServletRequest request, HttpServletResponse response, String identCode, String mobile, String typeName)
			throws IOException {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// 执行发送
			return smsService.createSmsToMobile(request, sr, mobile, null, typeName);
		} catch (Exception e) {
			log.warn("短信验证码发送异常:" + e.toString());
		}
		return sr;
	}

	// 发送短信验证码 & 图形码
	public ServiceResult smsCodeAndImgCode(HttpServletRequest request, HttpServletResponse response, String identCode, String mobile, String imgCode,
			String typeName) throws IOException {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// 校验-图形码
			if (!captchaService.validationCaptcha(request, sr, redis, imgCode)) {
				return sr;
			}
			// 执行发送
			return smsService.createSmsToMobile(request, sr, mobile, null, typeName);
		} catch (Exception e) {
			log.warn("短信验证码发送异常:" + e.toString());
		}
		return sr;
	}

}
